<?php

namespace app\admin\model;

use app\api\model\wanlshop\Article;
use app\admin\model\wanlshop\Share;
use app\api\model\wanlshop\UserInvitation;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\UserFinanceLog;
use think\Exception;
use think\exception\DbException;
use think\Model;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text',
        'createtime_text'
    ];

    public function getOriginData()
    {
        return $this->origin;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double)$changedata['money'] !== (double)$origin['money'])) {
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
            if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
        });
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['prevtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['logintime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['createtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['jointime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     *  介绍
     */

    public function introduce()
    {
        return $this->belongsTo('UserIntroduce', 'introduce_id', 'id', [], 'LEFT');
    }

    /**
     * @param $where
     * @param $score
     * @throws \think\Exception
     * 增加用户积分
     */
    public function addingUserCredits($where, $score, $event = 'sys', $rel_id = 0)
    {
        $user = self::find($where['id']);
        UserFinanceLog::addRecord([[
            'user_id' => $where['id'],
            'admin_id' => 0,
            'type' => 'score',
            'flag' => 'add',
            'value' => $score,
            'before' => $user->score,
            'after' => bcadd($user->score, $score, 2),
            'event' => 'pay',
            'rel_id' => $rel_id,
            'status' => 'succeed',
            'createtime' => time(),
            'updatetime' => time()
        ]]);
        $this->where($where)->setInc("score", $score);
    }

    /**
     *  转介绍
     */
    public function getMyIntroduce($uid)
    {
        $where['id'] = $uid;
        $res = $this->field('id, nickname, avatar, user_code, introduce_id, invitation_code')
            ->with(['introduce' => function ($query) {
                $query->withField('id, accumulative_total, stay, invite_number, withdrawing, withdrawed, may_withdraw, partner_number, rule');
            }])
            ->where($where)
            ->find();
        if (!$res['introduce']) {
            $res['introduce'] = [
                'id' => 0,
                'uid' => 0,
                'accumulative_total' => 0.00,
                'stay' => 0.00,
                'invite_number' => 0,
                'withdrawing' => 0.00,
                'withdrawed' => 0.00,
                'may_withdraw' => 0.00,
                'partner_number' => 0,
                'rule' => Article::where('category_id', 182)->order('updatetime', 'desc')->value('content'),
                'createtime' => 0
            ];
        }

        return $res;
    }


    /**
     * 合作伙伴
     * @param $uid
     * @param $page
     * @param $pageSize
     * @return array
     * @throws Exception
     * @throws DbException
     */
    public function getPartnerList($uid, $page, $pageSize)
    {
        $model = new UserInvitation();
        // 条件
        $where['user_id'] = $uid;
        // 总条数
        $count = $model->where($where)->count();
        // 数据
        return $model
            ->with(['user' => function ($query) {
                $query->withField('id,username,nickname,email,mobile,avatar');
            }])
            ->where($where)
            ->order("createtime desc")
            ->paginate($pageSize, $count, ['page' => $page])
            ->each(function ($item) {
                $item->createtime = date('Y-m-d H:i:s', $item->createtime);
                return $item;
            })
            ->toArray();
    }

    public function share()
    {
        return $this->belongsTo(Share::class, 'user_id', 'id');
    }

}
